package com.hicorp.segment.component;

import com.alibaba.fastjson.JSON;
import com.hicorp.segment.service.impl.BaseInterfaceImpl;
import com.hicorp.segment.utils.ResultBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @author websocket服务
 */
@ServerEndpoint(value = "/basic-request/{tableName}")
@Component
public class WebSocketServer {
    public static WebSocketServer webSocketServer;

    @Autowired
    private BaseInterfaceImpl baseInterface;


    @PostConstruct
    public void init() {
        webSocketServer = this;
    }

    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    /**
     * 记录当前在线连接数
     */
    public static final Map<String, List<Session>> sessionMap = new ConcurrentHashMap<>();
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("tableName") String tableName,@PathParam("queryBy") String queryBy) {
        if(sessionMap.get(tableName)==null){
            sessionMap.put(tableName,new ArrayList<>(){{
                add(session);
            }});
        }
        else{
            sessionMap.get(tableName).add(session);
        }
        log.info("有新用户加入，username={}, 当前在线人数为：{}", session, sessionMap.size());
        ResultBean<List<?>> resultBean = webSocketServer.baseInterface.queryAll(tableName);
        sendMessage(JSON.toJSONString(resultBean.getData()),session);  // 后台发送消息给客户端
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("tableName") String tableName) {
        sessionMap.get(tableName).remove(session);
        log.info("有一连接关闭，移除username={}的用户session, 当前在线人数为：{}", session, sessionMap.size());
    }

    /**
     * 收到客户端消息后调用的方法
     * 后台收到客户端发送过来的消息
     * onMessage 是一个消息的中转站
     * 接受 浏览器端 socket.send 发送过来的 json数据
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session, @PathParam("tableName") String tableName) {
        log.info("服务端收到要发往用户username={}的消息:{}", tableName, message);
        List<Session> toSession = sessionMap.get(tableName);
        if (toSession != null) {
            this.sendAllMessage(message, toSession);
            log.info("发送给用户username={}，消息：{}", tableName, message);
        } else {
            log.info("发送失败，未找到用户username={}的session", tableName);
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 服务端发送消息给客户端
     */
    private void sendMessage(String message, Session toSession) {
        try {
            log.info("服务端给客户端[{}]发送消息{}", toSession.getId(), message);
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败", e);
        }
    }

    /**
     * 服务端发送消息给所有客户端
     */
    private void sendAllMessage(String message,List<Session> sessionList) {
        try {
            for (Session session : sessionList) {
                log.info("服务端给客户端[{}]发送消息{}", session.getId(), message);
                session.getBasicRemote().sendText(message);
            }
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败", e);
        }
    }
}
